import React from 'react';
import {Card, Table, Form, Row, Col, Button, DatePicker, Tabs, Spin} from 'antd';
import PropTypes from 'prop-types';
import {TABLE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, FORM_ROW_OPTIONS, FORM_OPTIONS} from '../constants';
import styles from './style.css';
import moment from 'moment';
import {injectIntl} from './intl';
import {addMonths} from './utils';
import {conventEnumValueToString, formatPercent} from '../utils';
import TagSelect from 'Shared/components/TagSelect';
import {partChannel} from '../Enum';
import DataSet from '@antv/data-set';
import {Chart, Geom, Axis, Tooltip, Legend, Label, View} from 'bizcharts';
const {MonthPicker} = DatePicker;
const FormItem = Form.Item;
const {TabPane} = Tabs;

export class TablePanelWeek extends React.PureComponent {
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearchCountry(value);
    }
    disabledDate = current => current && current > moment().endOf('day')
    onChange = (value, name) => {
        this.props.onConditionsChange(name, value);
        this.props.querySearchCountry(value);
    }
    onChangeMonthPicker = (value, name) => {
        this.props.onConditionsChange('monthweek', name);
    }
    onClickLegend = (ev, legendItems) => {
        setTimeout(() => {
            const checked = ev.checked;
            const value = ev.item.value;
            if(value === '满足率')
                if(checked) {
                    this.chart.get('views')[0].get('geoms')[0].show();
                } else {
                    this.chart.get('views')[0].get('geoms')[0].hide();
                }
            const newLegend = legendItems.map(d => {
                if(d.value === value)
                    return Object.assign({}, d, {
                        checked,
                    });
                return d;
            });
            this.chart.filter('type', t => {
                const legendCfg = newLegend.find(i => i.value === t);
                return legendCfg && legendCfg.checked;
            });
            
            this.chart.legend({
                items: newLegend
            });
            this.chart.repaint();
        }, 0);
    }
    render() {
        const {
            dataCountry,
            initEnum,
            conditions,
            loadingCountry,
            loadingWeek,
            dataWeek,
            hasError
        } = this.props;
        const columnsCountry = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.channel',
                    defaultMessage: '渠道'
                }),
                dataIndex: 'channel',
                render: (text, record) => ({
                    children: conventEnumValueToString(partChannel, text),
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.type',
                    defaultMessage: '分类'
                }),
                dataIndex: 'type'
            }, {
                title: addMonths(5, conditions.month),
                dataIndex: 'n1MonthNumber',
                render: (text, record, index) => ({
                    children: index === 6 ? formatPercent(text || 0) : text,
                    props: {},
                })
            }, {
                title: addMonths(4, conditions.month),
                dataIndex: 'n2MonthNumber',
                render: (text, record, index) => ({
                    children: index === 6 ? formatPercent(text || 0) : text,
                    props: {},
                })
            }, {
                title: addMonths(3, conditions.month),
                dataIndex: 'n3MonthNumber',
                render: (text, record, index) => ({
                    children: index === 6 ? formatPercent(text || 0) : text,
                    props: {},
                })
            }, {
                title: addMonths(2, conditions.month),
                dataIndex: 'n4MonthNumber',
                render: (text, record, index) => ({
                    children: index === 6 ? formatPercent(text || 0) : text,
                    props: {},
                })
            }, {
                title: addMonths(1, conditions.month),
                dataIndex: 'n5MonthNumber',
                render: (text, record, index) => ({
                    children: index === 6 ? formatPercent(text || 0) : text,
                    props: {},
                })
            }, {
                title: addMonths(0, conditions.month),
                dataIndex: 'n6MonthNumber',
                render: (text, record, index) => ({
                    children: index === 6 ? formatPercent(text || 0) : text,
                    props: {},
                })
            }];
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.channel',
                    defaultMessage: '渠道'
                }),
                dataIndex: 'channel',
                render: (text, record) => ({
                    children: conventEnumValueToString(partChannel, text),
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.type',
                    defaultMessage: '分类'
                }),
                dataIndex: 'type'
            }, {
                title: moment(dataWeek.fridayOne).format('MM-DD'),
                dataIndex: 'n1WeekNumber'
            }, {
                title: moment(dataWeek.fridayTwo).format('MM-DD'),
                dataIndex: 'n2WeekNumber',
            }, {
                title: moment(dataWeek.fridayThree).format('MM-DD'),
                dataIndex: 'n3WeekNumber'
            }, {
                title: moment(dataWeek.fridayFour).format('MM-DD'),
                dataIndex: 'n4WeekNumber'
            }];
        if(dataWeek.fridayFive)
            columns.push({
                title: moment(dataWeek.fridayFive).format('MM-DD'),
                dataIndex: 'n5WeekNumber'
            });
        const firstColumns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.dealerCode',
                    defaultMessage: '总代'
                }),
                dataIndex: 'dealerCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.country',
                    defaultMessage: '国家'
                }),
                dataIndex: 'country',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.channel',
                    defaultMessage: '渠道'
                }),
                dataIndex: 'channel',
                render: (text, record) => ({
                    children: conventEnumValueToString(partChannel, text),
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.type',
                    defaultMessage: '分类'
                }),
                dataIndex: 'type'
            }, {
                title: moment(dataWeek.fridayOneLast).format('MM-DD'),
                dataIndex: 'lastWeekNumber'
            }, {
                title: moment(dataWeek.fridayOne).format('MM-DD'),
                dataIndex: 'weekNumber',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.newNumber',
                    defaultMessage: '新增项目'
                }),
                dataIndex: 'newNumber'
            }, {
                title: this.props.intl.formatMessage({
                    id: 'tablePanel.column.totalNumber',
                    defaultMessage: '合计项'
                }),
                dataIndex: 'totalNumber'
            }];
        const countryCrop = [];
        dataCountry.forEach(item => {
            const dataRateBak = item.detailRates.map(v => ({
                month: v.month,
                BO品种: v.variety,
                BO交付品种: v.deliveryVariety,
                满足率: v.rate
            }));
            //柱状图与折线图
            const dsRate = new DataSet();
            dsRate.setState('type', '');
            const dvRate = dsRate.createView().source(dataRateBak);
            
            dvRate.transform({
                type: 'fold',
                fields: ['BO品种', 'BO交付品种'], // 展开字段集
                key: 'type', // key字段
                value: 'value', // value字段
            })
                .transform({
                    type: 'filter',
                    callback: d => d.type !== dsRate.state.type
                });
            const scale = {
                满足率: {
                    type: 'linear',
                    formatter: val => `${val}%`,
                    tickCount: 10,
                    // ticks: ['0', '10', '20', '30', '40', '50', '60', '70', '80', '90', '100'],
                    // min: 0,
                    // max: 1,
                },
                value: {
                    alias: 'BO\n满\n足\n率'
                }
            };
            
            const legendItems = [
                {
                    value: 'BO品种',
                    marker: {
                        symbol: 'square',
                        fill: '#3182bd',
                        radius: 5
                    }
                },
                {
                    value: 'BO交付品种',
                    marker: {
                        symbol: 'square',
                        fill: '#41a2fc',
                        radius: 5
                    }
                },
                {
                    value: '满足率',
                    marker: {
                        symbol: 'hyphen',
                        stroke: '#fad248',
                        radius: 5,
                        lineWidth: 3
                    },
                    checked: true
                },
            ];
            const chart = (
                <Chart height={450} width={400}
                    padding={['8%', '8%', '18%']} forceFit data={dvRate} scale={scale}
                    onGetG2Instance={c => {
                        this.chart = c;
                    }}>
                    <Legend
                        custom
                        clickable={false}
                        hoverable={false}
                        allowAllCanceled
                        items={legendItems}
                        onClick={ev => this.onClickLegend(ev, legendItems)} />
                    <Axis name="month" />
                    <Axis name="value" position={'left'} />
                    <Tooltip />
                    <Geom
                        type="interval"
                        position="month*value"
                        color={['type', value => {
                            if(value === 'BO品种')
                                return '#2b6cbb';
                            if(value === 'BO交付品种')
                                return '#41a2fc';
                        }]}
                        adjust={[{
                            type: 'dodge',
                            marginRatio: 1 / 32,
                        }]} >
                        <Label
                            content="value"
                            textStyle={{
                                textAlign: 'center', // 文本对齐方向，可取值为： start middle end
                                fill: '#404040', // 文本的颜色
                                fontSize: '12', // 文本大小
                            }}/>
                    </Geom>
                    <View data={dataRateBak} >
                        <Axis name="满足率" position="right" />
                        <Geom type="line" position="month*满足率" color="#fad248" size={3} >
                            <Label
                                content="满足率"
                                textStyle={{
                                    textAlign: 'start', // 文本对齐方向，可取值为： start middle end
                                    fill: '#404040', // 文本的颜色
                                    fontSize: '12', // 文本大小
                                }}/>
                        </Geom>
                    </View>
                </Chart>
            );
            countryCrop.push(
                <Card.Grid key={item.id}>
                    <Card
                        bodyStyle={{
                            padding: 0
                        }}
                        bordered={false}
                        loading={loadingCountry}>
                        <Card.Meta
                            title={<Row>
                                <Col>
                                    {item.country}
                                </Col>
                            </Row>}
                            description={<div>
                                <div>{chart}</div>
                                <div className={styles.divmargintop}>
                                    <Table
                                        className="white-space-nowrap"
                                        rowKey="id"
                                        dataSource={item.details}
                                        columns={columnsCountry}
                                        loading={loadingCountry}
                                        pagination={false}
                                        {...TABLE} />
                                </div>
                            </div>}/>
                    </Card>
                </Card.Grid>
            );
        });
        return (
            <Spin spinning={this.props.loadingWeek || this.props.loadingCountry}>
                <Card className={styles.projectGrid}>
                    <Form className="form-standard">
                        <Tabs defaultActiveKey="1">
                            <TabPane tab={this.props.intl.formatMessage({
                                id: 'queryPanel.form.dealerquery',
                                defaultMessage: '总代汇总查询'
                            })} key="1">
                                <FormItem label={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.dealerId',
                                    defaultMessage: '总代'
                                })} {...FORM_ROW_OPTIONS.item}>
                                    <TagSelect
                                        name="dealerId"
                                        value={conditions.dealerId}
                                        options={initEnum.dealers}
                                        onChange={this.handleFilterChange} />
                                </FormItem>
                                <div className={styles.divHeight} />
                                {conditions.dealerId.length > 0 && countryCrop}
                            </TabPane>
                            <TabPane tab={this.props.intl.formatMessage({
                                id: 'queryPanel.form.week',
                                defaultMessage: '周汇总查询'
                            })} key="2">
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={this.props.intl.formatMessage({
                                                id: 'queryPanel.form.monthweek',
                                                defaultMessage: '年月'
                                            })}
                                            {...FORM_OPTIONS.item}>
                                            <MonthPicker
                                                allowClear={false}
                                                placeholder="Select Month"
                                                disabledDate={this.disabledDate}
                                                value={this.props.conditions.monthweek ? moment(this.props.conditions.monthweek) : undefined}
                                                name={this.props.conditions.monthweek}
                                                onChange={this.onChangeMonthPicker} />
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col>
                                        <FormItem label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })} {...FORM_ROW_OPTIONS.item}>
                                            <TagSelect
                                                name="dealerId"
                                                value={conditions.dealerId}
                                                options={initEnum.dealers}
                                                onChange={this.onChange} />
                                        </FormItem>
                                    </Col>
                                </Row>
                                <Row>
                                    <Col>
                                        <Button key="query" type="primary" onClick={this.props.querySearchWeek} loading={loadingWeek}>{this.props.intl.formatMessage({
                                            id: 'queryPanel.btn.query',
                                            defaultMessage: '查询'
                                        })}</Button>
                                    </Col>
                                </Row>
                                <div className={styles.divHeight} />
                                {
                                    dataWeek.isFirstQty && <Table
                                        className="white-space-nowrap"
                                        rowKey="id"
                                        dataSource={dataWeek.fistWeekDetails}
                                        columns={firstColumns}
                                        loading={loadingWeek}
                                        pagination={false}
                                        {...TABLE}
                                        locale={{
                                            emptyText: hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                                        }} />
                                }
                                {
                                    !dataWeek.isFirstQty && <Table
                                        className="white-space-nowrap"
                                        rowKey="id"
                                        dataSource={dataWeek.weekDetails}
                                        columns={columns}
                                        loading={loadingWeek}
                                        pagination={false}
                                        {...TABLE}
                                        locale={{
                                            emptyText: hasError ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
                                        }} />
                                }
                            </TabPane>
                        </Tabs>
                    </Form>
                </Card>
            </Spin>
        );
    }
}

TablePanelWeek.propTypes = {
    conditions: PropTypes.object.isRequired,
    dataCountry: PropTypes.array.isRequired,
    querySearchCountry: PropTypes.func.isRequired,
    querySearchWeek: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    hasError: PropTypes.string,
    intl: PropTypes.object,
    loadingCountry: PropTypes.bool,
    loadingWeek: PropTypes.bool,
};

import {connect} from 'react-redux';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
import {saveQueryCondition, querySearchCountry, querySearchWeek} from './actions';

const getInitData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'data']),
    init => {
        const initData = init.toJS();
        const dealers = initData ? initData.map(item => ({
            text: `${'('}${item.code}${')'}${item.country}`,
            value: item.id
        })) : [];
        return {
            dealers
        };
    }
);
const getDataCountry = selectorFactory(['page', 'domainData', 'listCountry', 'data']);
const getDataWeek = selectorFactory(['page', 'domainData', 'listWeek', 'data']);
const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const mapStateToProps = state => ({
    dataCountry: getDataCountry(state),
    dataWeek: getDataWeek(state),
    loadingCountry: state.getIn(['page', 'domainData', 'listCountry', 'isFetching']),
    loadingWeek: state.getIn(['page', 'domainData', 'listWeek', 'isFetching']),
    hasError: state.getIn(['page', 'domainData', 'listCountry', 'hasError']),
    initEnum: getInitData(state),
    conditions: getConditions(state),
});
const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    querySearchCountry: value => dispatch(querySearchCountry(value)),
    querySearchWeek: value => dispatch(querySearchWeek(value)),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(TablePanelWeek));
